package cn.org.exam.controller.auth;

import cn.org.exam.common.result.Result;
import cn.org.exam.common.util.JwtUtil;
import cn.org.exam.common.util.PasswordUtil;
import cn.org.exam.model.entity.Role;
import cn.org.exam.model.entity.User;
import cn.org.exam.model.form.LoginForm;
import cn.org.exam.model.vo.LoginVO;
import cn.org.exam.model.vo.MeVO;
import cn.org.exam.service.UserService;
import io.jsonwebtoken.Claims;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final UserService userService;

    public AuthController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 登录接口
     */
    @PostMapping("/login")
    public Result<LoginVO> login(@Valid @RequestBody LoginForm form) {

        // 1. 根据用户名查用户
        User user = userService.findByUsername(form.getUsername());
        if (user == null) {
            return Result.fail("用户名或密码错误");
        }

        // 2. 校验密码
        if (!PasswordUtil.matches(form.getPassword(), user.getPassword())) {
            return Result.fail("用户名或密码错误");
        }

        if (Boolean.FALSE.equals(user.getEnabled())) {
            return Result.fail("账号已被禁用");
        }

        // 3. 生成 token
        String token = JwtUtil.generateToken(user);

        // 4. 取角色 code 列表
        List<String> roleCodes = (user.getRoles() == null)
                ? Collections.emptyList()
                : user.getRoles().stream().map(Role::getCode).collect(Collectors.toList());

        // 5. 封装返回
        LoginVO vo = new LoginVO();
        vo.setToken(token);
        vo.setId(user.getId());
        vo.setUsername(user.getUsername());
        vo.setNickname(user.getNickname());
        vo.setRoles(roleCodes);

        return Result.ok(vo);
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/me")
    public Result<MeVO> me(@RequestHeader("Authorization") String authHeader) {

        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return Result.fail("缺少或格式错误的 Authorization Header");
        }

        String token = authHeader.substring(7);

        Claims claims;
        try {
            claims = JwtUtil.parseToken(token);
        } catch (Exception e) {
            return Result.fail("无效或过期的 token");
        }

        Long userId = claims.get("uid", Long.class);

        User user = userService.findById(userId);
        if (user == null) {
            return Result.fail("用户不存在");
        }

        List<String> roleCodes = (user.getRoles() == null)
                ? Collections.emptyList()
                : user.getRoles().stream().map(Role::getCode).collect(Collectors.toList());

        MeVO vo = new MeVO();
        vo.setId(user.getId());
        vo.setUsername(user.getUsername());
        vo.setNickname(user.getNickname());
        vo.setRoles(roleCodes);

        return Result.ok(vo);
    }
}
